package com.zzstm.educenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.zzstm.commonUtils.Base64EnCodeAndDecode;
import com.zzstm.commonUtils.JwtUtils;
import com.zzstm.educenter.entity.UcenterMember;
import com.zzstm.educenter.service.UcenterMemberService;
import com.zzstm.educenter.utils.ConstantUtils;
import com.zzstm.educenter.utils.HttpClientUtils;
import com.zzstm.servicebase.ex.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    //获取扫描人信息
    @GetMapping("/callback")
    public String callback(String code,String state){
        try {
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantUtils.WX_OPEN_APP_ID,
                    ConstantUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //使用httpclient得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //转换为map集合，根据key得到access_token和openid
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            //判断用户是否已注册
            QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
            wrapper.eq("openid",openid);
            UcenterMember user = memberService.getOne(wrapper);
            if (user == null){  //没有注册，获取信息并注册
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //发送请求,得到用户信息
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //得到用户信息中需要的信息
                HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) mapUserInfo.get("nickname");
                String avatar = (String) mapUserInfo.get("headimgurl");
                user = new UcenterMember();
                //微信昵称有特殊字符如 秘制钢化蛋🥚 时加入数据库会报错，将昵称进行base64编码再存入，取出时再解码
                nickname = Base64EnCodeAndDecode.encode(nickname);
                user.setNickname(nickname);
                user.setAvatar(avatar);
                user.setOpenid(openid);
                memberService.save(user);
            }

            //使用jwt返回用户信息
            String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getNickname());

            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"登录失败");
        }


    }

    //生成wx二维码
    @GetMapping("/login")
    public String getWxCode(){
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = ConstantUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(
                baseUrl,
                ConstantUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "zzstm"
        );
        return "redirect:" + url;
    }

}
